package com.dddd.blog.blogcommon.interceptor;

import com.dddd.blog.blogcommon.annotation.ResponseResult;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


/**
 * 全局控制器响应拦截器
 * @author 喵星球的大橘
 */
public class GlobalResponseInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取控制器对象的类信息、方法
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Class<?> beanClass = handlerMethod.getBeanType();
            Method method = handlerMethod.getMethod();

            // 判断被访问的控制器是否被注解修饰
            if(beanClass.isAnnotationPresent(ResponseResult.class)){
                // 给请求添加标记，表示需要返回统一的响应
                request.setAttribute("RESPONSE-API-ANNO", beanClass.getAnnotation(ResponseResult.class));
            }else if(method.isAnnotationPresent(ResponseResult.class)){
                request.setAttribute("RESPONSE-API-ANNO", beanClass.getAnnotation(ResponseResult.class));
            }
        }

        return true;
    }

}
